﻿/* File Created: July 27, 2012 

 jQuery Infinite Scroll plugin 1.0

 Copyright (c) 2012 ERPStore

 Usage :

 $("#div").infiniteScroll({
	scrollUrl : '', // Url for get next partial page
	data : '', // Parameters posted on Url must containt pageIndex paramater
	pageMax : '', // Count of max page to scroll
	onsuccess : null, // Event raised when partial content is loaded
	onbeforeappend : null, // Event raised when partial content is appended
	onloading : null, // Event raised at begin of load data
 });

*/

;(function ($) {

$.fn.infiniteScroll = function (options) {

	if (this.length > 1) {
		this.each($(this).infiniteScroll(options));
		return this;
	}
	
	var settings = $.extend({} , $.fn.infiniteScroll.defaultOptions, options);
	var pagingload = false;
	var pageIndex = 1;
	var div = $(this);

	$(window).scroll(function () {
		var sbottom = $(document).height() - $(window).height() - 200;
		if ($(window).scrollTop() >= sbottom && !pagingload) {
			if (pageIndex >= settings.pageMax) {
				return;
			}
			pagingload = true;
			var isMaxPage = (settings.pageIndex == settings.pageMax);
			var params = [ pageIndex, isMaxPage ];
			settings.onloading.apply(div,params);
			settings.data.pageIndex = pageIndex;
			$.ajax({
				type: 'POST',
				contentType: 'application/json',
				url: settings.scrollUrl,
				data: JSON.stringify(settings.data),
				success: function (data) {
					pageIndex++;
					settings.onbeforeappend.apply(div, params);
					div.append(data);
					settings.onsuccess.apply(div, params);
					pagingload = false;
				}
			});
		}
	});

	return this;
}

$.fn.infiniteScroll.defaultOptions = {
	scrollUrl: '',
	data: null,
	pageMax: 1,
	onsuccess: function (pageIndex, isMaxPage) { },
	onbeforeappend: function(pageIndex, isMaxPage) { },
	onloading : function(pageIndex, isMaxPage) { }
};


})(jQuery);